const { spawn } = require('child_process');
const fs = require('fs');
const path = require('path');

// 测试Whisper功能的脚本
async function testWhisper() {
  console.log('Testing Whisper functionality...');
  
  // 检查是否存在测试音频文件
  const testAudioPath = path.join(__dirname, '../input/mp3/kCtDawsZ.mp4');
  if (!fs.existsSync(testAudioPath)) {
    console.error('Test audio file not found:', testAudioPath);
    return;
  }
  
  console.log('Using audio file:', testAudioPath);
  
  // 创建模型目录
  const modelDir = path.join(__dirname, '../temp/whisper_models');
  if (!fs.existsSync(modelDir)) {
    fs.mkdirSync(modelDir, { recursive: true });
  }
  
  // 构建调用Whisper的命令
  const command = `python -m whisper "${testAudioPath}" --model base --model_dir "${modelDir}" --language en --verbose True --output_dir "${path.join(__dirname, '../temp')}"`;
  
  console.log('Running command:', command);
  
  // 使用spawn执行命令
  const child = spawn('python', [
    '-m', 'whisper',
    testAudioPath,
    '--model', 'base',
    '--model_dir', modelDir,
    '--language', 'en',
    '--verbose', 'True',
    '--output_dir', path.join(__dirname, '../temp')
  ]);
  
  // 监听stdout输出
  child.stdout.on('data', (data) => {
    process.stdout.write(`stdout: ${data}`);
  });
  
  // 监听stderr输出
  child.stderr.on('data', (data) => {
    process.stderr.write(`stderr: ${data}`);
  });
  
  // 监听进程结束
  child.on('close', (code) => {
    console.log(`\nWhisper process exited with code ${code}`);
    if (code === 0) {
      console.log('Whisper transcription completed successfully');
      
      // 检查生成的文件
      const outputFiles = [
        path.join(__dirname, '../temp/kCtDawsZ.mp4.txt'),
        path.join(__dirname, '../temp/kCtDawsZ.mp4.vtt'),
        path.join(__dirname, '../temp/kCtDawsZ.mp4.srt')
      ];
      
      outputFiles.forEach(file => {
        if (fs.existsSync(file)) {
          console.log(`Generated file: ${file}`);
          
          // 显示前几行内容
          if (file.endsWith('.txt')) {
            const content = fs.readFileSync(file, 'utf8');
            console.log(`First 500 characters of transcription:\n${content.substring(0, 500)}...`);
          }
        }
      });
    } else {
      console.error('Whisper transcription failed');
    }
  });
  
  // 监听进程错误
  child.on('error', (error) => {
    console.error('Failed to start Whisper process:', error);
  });
}

// 运行测试
testWhisper().catch(console.error);